#include <stdio.h>
#include "ohos_init.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#include "cmsis_os2.h"

#define BUTTON_GPIO 11
#define LED_GPIO 7

/*
*   这是基于轮询方式的按钮处理
*   这个实验用小台灯板
*/
int lastv = 0;

int led_state = 1;
void button(void* args ){
    printf("button thread running...");
    IoTGpioInit(BUTTON_GPIO);
    IoTGpioSetDir(BUTTON_GPIO,IOT_GPIO_DIR_IN);
    IoTGpioSetPull(BUTTON_GPIO,IOT_GPIO_PULL_UP);
    IoTGpioSetFunc(BUTTON_GPIO,IOT_GPIO_FUNC_GPIO_11_GPIO);


    IoTGpioInit(LED_GPIO);
    IoTGpioSetDir(LED_GPIO,IOT_GPIO_DIR_OUT);
    IoTGpioSetFunc(LED_GPIO,IOT_GPIO_FUNC_GPIO_7_GPIO);

    int v;

    while(1){
        IoTGpioGetInputVal(BUTTON_GPIO,&v);
        printf("read data 0x%x \n",v);
        usleep(200*1000);
        
        if(lastv == 1 && v == 0){
            IoTGpioSetOutputVal(LED_GPIO,led_state);
            led_state = 1 - led_state;
        }

        lastv = v;
    }
}

void button_entry(){
    printf("button_entry calbutton \n");

    osThreadAttr_t attr;

    attr.name = "thread_button";
    attr.attr_bits = 0U; // 如果为1 ，则可以使用osThreadJoin函数
    attr.cb_mem = NULL; //控制快的指针
    attr.cb_size = 0U;
    attr.stack_mem = NULL; //栈内存指针
    attr.stack_size = 1024 * 4; //栈大小
    attr.priority = 25; //优先级

    if (osThreadNew((osThreadFunc_t)button, NULL, &attr) == NULL)
    {
        printf("Falied to create thread!\n");
    }


}

APP_FEATURE_INIT(button_entry);

